package com.zues.thread.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * 演示可重入锁
 *
 * @author zues
 * @date 12/7/2024 11:38 下午
 */
@Slf4j(topic = "c.ReentrantLockDemo")
public class ReentrantLockDemo {


    public synchronized void add() {
        add();
    }

    public static void main(String[] args) {
        //可重入锁会造成循环递归调用，造成栈溢出异常
//        new ReentrantLockDemo().add();

//        Object o = new Object();
//        new Thread(() -> {
//            synchronized (o) {
//                log.info("{} 最外层", Thread.currentThread().getName());
//                synchronized (o) {
//                    log.info("{} 中层", Thread.currentThread().getName());
//                    synchronized (o) {
//                        log.info("{} 内层", Thread.currentThread().getName());
//                    }
//                }
//            }
//        }, "t1").start();

        /*
         * 使用lock演示可重入锁
         */
        ReentrantLock reentrantLock = new ReentrantLock();
        new Thread(() -> {
            try {
                reentrantLock.lock();
                log.info("{} 最外层", Thread.currentThread().getName());
                try {
                    reentrantLock.lock();
                    log.info("{} 中层", Thread.currentThread().getName());
                }finally {
                    //这里不释放会造成其他使用这个锁的线程阻塞
                    reentrantLock.unlock();
                }

            }catch (Exception e){
                e.printStackTrace();
            }finally {
                reentrantLock.unlock();
            }
        }, "t1").start();

        //创建新线程
        new Thread(() -> {
            reentrantLock.lock();
            log.info("{} 1111111111", Thread.currentThread().getName());
            reentrantLock.unlock();
        }, "aa").start();
    }


}
